<?php


namespace app\admin\controller;


use app\admin\service\AdminService;
use app\admin\service\AuthRuleService;
use app\common\controller\BaseAdmin;
use app\admin\model\Admin as AdminModel;
use think\facade\Config;
use think\crypt\Crypt;

class Index extends BaseAdmin
{


    public function index(){
        $this->checkLogin();

        //获取登录用户信息
        $this->assign('admin',AdminService::getLoginInfo());

        //头部菜单
        $this->assign('navBar',AuthRuleService::authMenu($this->auth_uid,true));
        return $this->fetch();
    }


    /**
     * 权限菜单
     * @return \think\response\Json
     */
    public function menu(){
        return json(AuthRuleService::authMenu($this->auth_uid));
    }

    /**
     * 监测后台登录账号是否存在
     */
    public function check(){
        if ($this->request->isAjax()){
            $username = $this->request->post('username');
            $admin = AdminModel::where('username|email',$username)->find();
            if (!$admin){
                $this->error('账号不存在');
            }
            if ($admin['state']==0){
                $this->error('账号已冻结请联系管理员');
            }
            $this->success('用户正常');
        }
    }

    /**
     * 后台管理员登录
     * @return array|string
     * @throws \Exception
     */
    public function login(){
        if ($this->request->isAjax()){
            $data = $this->request->post();
            return AdminService::login($data);
        }
        return $this->fetch();
    }

    public function remember(){
        if(!cookie('remember')){
            return json(['code'=>1,'data'=>[]]);
        }
        $remember = Crypt::decrypt(cookie('remember'),Config::get('login_admin.crypt'));
        return json(['code'=>1,'data'=>unserialize($remember)]);
    }

    /**
     * 退出登录
     */
    public function logout(){
        AdminService::logout();
       return json(['code'=>0,'msg'=>'成功退出','data'=>[]]);
    }

    /**
     * 控制台
     * @return string
     * @throws \Exception
     */
    public function console(){
        return $this->fetch();
    }
}